using CsGL.OpenGL;
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace TagTool.OpenGL
{

	public sealed class View : OpenGLControl 
	{
		private readonly Model model;
		private bool isDisposed = false;

		App app;
		public View(Model inheritedModel, App app) 
		{
			this.app = app;
			model = inheritedModel;
		}

		protected override void Dispose(bool disposing) 
		{
			if(!isDisposed) 
			{
				if(disposing)
				{
					GC.SuppressFinalize(this);
				}
				base.Dispose(disposing);
			}
			isDisposed = true;
		}

		~View() 
		{
			Dispose(false);
		}

		protected override OpenGLContext CreateContext() 
		{
			ControlGLContext context = new ControlGLContext(this);
			
			DisplayType displayType = new DisplayType(app.ColorDepth, app.ZDepth, app.StencilDepth, app.AccumDepth);
			context.Create(displayType, null);
			return context;
		}

		public override void glDraw() 
		{
			model.Draw();																// Have The Control Draw Our Model
		}
		
		public void Redraw() 
		{
            if (!isDisposed)
            {
                OnPaint(null);																// Force Painting
            }
		}

		public void Screenshot()
		{
			try {
				if(!File.Exists(model.GetType().FullName + ".jpg")) {					// If The Filename Doesn't Exist
					Image image = Context.ToImage();									// Create An Image From The OpenGL Context
					image.Save(model.GetType().FullName + ".jpg", ImageFormat.Jpeg);	// Save The Image
					image.Dispose();													// Get Rid Of The Image Object
				}
				else {																	// Otherwise
					int x = 0;															// Let's Add A Number To The Filename
					while(File.Exists(model.GetType().FullName + "_" + x + ".jpg")) {	// While This New Filename Exists
						x++;															// Increase The Number
					}
					Image image = Context.ToImage();									// Create An Image From The OpenGL Context
					// Save The Image
					image.Save(model.GetType().FullName + "_" + x + ".jpg", ImageFormat.Jpeg);
					image.Dispose();													// Get Rid Of The Image Object
				}
			}
			catch(Exception e)
			{
				string errorMsg = "An Error Occurred While Saving Screenshot.\n\n\nStack Trace:\n\t" + e.StackTrace + "\n";
				MessageBox.Show(errorMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				app.Terminate();
			}
		}

		protected override void OnSizeChanged(EventArgs e) 
		{
			if(app.IsRunning) {															// If The App Is Running
				Size s = Size;	// Get The New Size
				if(s.Width!=0 && s.Height!=0)
					app.Model.Reshape((int) s.Width, (int) s.Height);						// Let The OpenGL Control Resize
			}
			base.OnSizeChanged(e);														// Let The Form Resize
		}
	}
}
